<template>
  <section>
    <el-card class="search-card">
      <BasicTableForm ref="formData"
        isScalingBtn
        :colNumOfRow="4"
        formItemWidth="120px"
        :formColumns="formItemList"
        :dataSource="formData"
        :defaultExpandStatus="false"
        :handleSearchForm="handleQueryForm" />
    </el-card>
    <el-card class="table-card">
      <basic-table
        showActionCol
        :showSelectCol="false"
        :loading="tableInfo.loading"
        :columns="tableInfo.columns"
        :dataSource="tableInfo.list"
        :pagination="pagination"
        :tableHeight="460"
        :actionColWidth="300"
        :actionRender="renderTableBtnAction"
        @pageChange="handlePageChange"
        @pageSizeChange="handlePageSizeChange"
      >
        <div slot="content_context">
          <el-button
            v-if="showBtn('导出') && supplierExportConfig.supplier"
            :disabled="!pagination.total"
            size="mini"
            type="primary"
            icon="el-icon-download"
            :loading="exporting"
            @click="handleExportFile"
            >导出</el-button>
          <el-button
            v-if="showBtn('新增')"
            size="mini"
            type="primary"
            @click="handleCreateSupplier"
            >新建线索供应商</el-button>
          <el-button
            size="mini"
            type="primary"
            class="right-btn"
            @click="handleConfigTableColumns"
            >字段显示设置</el-button>
        </div>
      </basic-table>
    </el-card>
    <el-dialog title="转化供应商" width="480px" :visible.sync="dialogFormVisible">
      <el-form :model="form">
        <el-form-item label="选择转化类型">
          <el-select v-model="form.type" placeholder="请选择转化类型">
            <el-option label="潜在供应商" value="潜在供应商"></el-option>
            <el-option label="合格供应商" value="合格供应商"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="corventClues">确 定</el-button>
      </div>
    </el-dialog>
    <ConvertSupplierDialog
      convertType="10"
      :supplier="supplier"
      :dialogVisible="dialogVisible"
      @handleClose="handleDialogClose" />
    <ConfigTableColumnsDialog
      :menuId="menuId"
      v-if="fieldSettingVisible"
      :dialogVisible="fieldSettingVisible"
      @handleClose="handleConfigTableColumnsDialogClose"
      @handleSubmit="hanldSubmitTableColumnsConfig" />
  </section>
</template>

<script>
import { mapGetters } from 'vuex';
import { getBtnsId } from '@/libs/btnsPermission';
import BasicTableForm from '@/components/supplier/BasicForm'; // 表单组件
import BasicTable from '@/components/supplier/BasicTable';
import BasicPage from '@/mixins/supplier/basicPage';
import ConfigTableColumnsDialog from '@/pages/supplier/components/configTableColumnsDialog';
import ConvertSupplierDialog from '@/pages/supplier/components/convertSupplierDialog'; // 转化弹窗
import {
  queryCluesSupplierListService,
  exportCluesSupplierFileService,
} from '@/api/supplier/management/cluesSupplier';
import {
  getListColumnSettings,
  supplierPreConvertCheck,
} from '@/api/supplier/components'
import { getHasIndexTableData } from '@/pages/supplier/utils/bizUtils';
import { createExcelByExport, handleOpenNewPage } from '@/utils/bizUtils';
import Dict from '@/mixins/supplier/dict';
import ManageArea from '@/mixins/supplier/manageArea';
import { INITIAL_FIELDS_VALUE, FORM_ITEM_LIST } from './constants'
const menuId = 320

export default {
  mixins: [Dict, ManageArea, BasicPage],
  components: {
    BasicTableForm,
    BasicTable,
    ConvertSupplierDialog,
    ConfigTableColumnsDialog,
  },
  computed: {
    ...mapGetters('permissions/systemBtns', ['showBtn']),
  },
  data () {
    return {
      menuId,
      formItemList: FORM_ITEM_LIST,
      tableInfo: {
        list: [],
        selection: [],
        columns: [],
        loading: false
      },
      pagination: {
        current: 1,
        total: 0,
        size: 10
      },
      formData: Object.assign({}, INITIAL_FIELDS_VALUE),
      // toolbarConfig: {
      //   slots: {
      //     // 自定义工具栏模板
      //     buttons: 'toolbar_buttons',
      //     tools: 'toolbar_tools'
      //   }
      // },
      exporting: false,
      dialogVisible: false,
      supplier: {},
      optionList: ['合格供应商', '潜在供应商'],
      value: undefined,
      dialogFormVisible: false,
      fieldSettingVisible: false,
      curRow: {},
      form: {

      }
    };
  },
  created () {
    this.getColSettings();
    this.getTableData();
  },
  methods: {
    // 获取列表配置
    async getColSettings () {
      const { status, message, result = [] } = await getListColumnSettings({ menuId })
      if (status === '0') {
        this.setTableColumns(result)
      } else {
        this.$message.error(message)
      }
    },
    // 应用列表配置
    setTableColumns (data) {
      const indexCol = { title: '序号', key: 'index', width: 50 }
      const arr = data.filter(i => i.isShow).map(i => {
        return {
          title: i.label,
          key: i.prop,
          width: i.width
        }
      })
      arr.unshift(indexCol)
      this.tableInfo.columns = arr.map((i) => {
        if (i.key === 'supplierName') {
          i.formatter = (row, column, cellValue, index) => {
            return <router-link target="_blank" to={{ name: 'viewCluesSupplier', query: { id: row.supplierId } }}>{ row.supplierName }</router-link>
          }
        }
        return i
      })
    },
    handleExportFile () {
      this.exporting = true
      exportCluesSupplierFileService(this.getRequestParams()).then(res => {
        this.exporting = false
        createExcelByExport({ excelTitle: '线索供应商信息', res })
      })
    },
    handleQueryForm () {
      this.getTableData(1);
    },
    // 页码切换
    handlePageChange (val) {
      this.getTableData(val);
    },
    // 每页条数切换
    handlePageSizeChange (val) {
      this.getTableData(1, val);
    },
    // 获取列表查询参数
    getRequestParams () {
      const {
        supplierCode = '',
        supplierName = '',
        mainCategoryId,
        manageCategoryId,
        mainProduct,
        supplierTypeId,
        belongDepartment,
        supplierManagerAreaId,
        createUser,
        invoiceType,
      } = this.formData
      return {
        supplierCode,
        supplierName,
        mainCategoryId,
        manageCategoryId,
        mainProduct,
        supplierTypeId,
        belongDepartment,
        supplierManagerAreaId,
        createUser,
        invoiceType,
      }
    },
    async getTableData (current = this.pagination.current, size = this.pagination.size) {
      sessionStorage.setItem('buttonId', getBtnsId('查询'));
      this.tableInfo.loading = true
      const params = Object.assign({ current, size }, this.getRequestParams())
      const resp = await queryCluesSupplierListService(params)
      this.tableInfo.loading = false
      if (resp && resp.result) {
        const { records, total, pages } = resp.result
        this.pagination = Object.assign(this.pagination, { current, size, total, pages })
        this.tableInfo.list = getHasIndexTableData(records, this.pagination)
      } else {
        this.tableInfo.list = []
      }
    },
    // 渲染表格操作栏按钮
    renderTableBtnAction (h, { row }) {
      return <div>
        <el-button type="text" disabled={!this.showBtn('编辑')} nativeOnClick={() => { this.handleEdit(row) }}>编辑</el-button>
        <el-button type="text" disabled={!this.showBtn('转化供应商')} nativeOnClick={() => { this.handleConvertSuppliers(row) }}>转化供应商</el-button>
        <el-button type="text" disabled={!this.showBtn('淘汰供应商')} nativeOnClick={() => { this.handleEliminateSuppliers(row) }}>淘汰供应商</el-button>
        <el-button type="text" nativeOnClick={() => { this.handleViewApprovalLog(row) }}>审批日志</el-button>
      </div>
    },
    // 新建线索供应商
    handleCreateSupplier () {
      // this.$router.push({ name: 'addCluesSupplier' });
      handleOpenNewPage(this, { name: 'addCluesSupplier' })
    },
    // 列表字段配置
    handleConfigTableColumns () {
      this.fieldSettingVisible = true;
    },
    // 字段显示设置弹窗关闭
    handleConfigTableColumnsDialogClose () {
      console.log('handleConfigTableColumnsDialogClose')
      this.fieldSettingVisible = false;
    },
    // 提交字段显示设置
    hanldSubmitTableColumnsConfig (data) {
      // console.log('hanldSubmitTableColumnsConfig', data)
      this.setTableColumns(data)
      this.fieldSettingVisible = false;
    },
    // 编辑
    handleEdit (data) {
      this.queryDataPermissionAction(data.supplierId).then(res => {
        if (res) {
          this.$router.push({ name: 'editCluesSupplier', query: { id: data.supplierId } });
        }
      })
    },
    // 转化供应商
    handleConvertSuppliers (data) {
      this.curRow = data
      this.dialogFormVisible = true
    },
    //  选择转化供应商
    async corventClues () {
      console.log('curRow :>> ', this.curRow);
      const { supplierId } = this.curRow
      if (this.form.type === '合格供应商') {
        console.log('合格供应商 operateType:>> ', 4);
        const { result } = await supplierPreConvertCheck({ supplierId, operateType: 4 })
        if (result === '1') {
          this.$router.push({ name: 'corventClues2Qualified', query: { id: this.curRow.supplierId } });
        } else {
          this.$message.error(result)
        }
      }
      if (this.form.type === '潜在供应商') {
        console.log('潜在供应商 operateType:>> ', 3);
        const { result } = await supplierPreConvertCheck({ supplierId, operateType: 3 })
        if (result === '1') {
          this.$router.push({ name: 'corventClues2Potential', query: { id: this.curRow.supplierId } });
        } else {
          this.$message.error(result)
        }
      }
    },
    // 淘汰供应商
    handleEliminateSuppliers (data) {
      // console.log(data)
      this.supplier = data
      this.dialogVisible = true
    },
    handleDialogClose (data) {
      // 关闭淘汰供应商弹窗
      this.dialogVisible = false
      if (data && data.status === '0') {
        this.$message.success('操作成功！')
        this.getTableData()
      }
    },
    // 审批日志
    handleViewApprovalLog (data) {
      this.$router.push({ name: 'auditLog', query: { supplierId: data.supplierId } });
    },
  },
}
</script>

<style lang="less" scope>
.right-btn {
  float: right;
}
</style>
